<template>
	<view class="switchWallet" v-if="walletChain">
		<view class="titleBox">
			<view class="search">
				<!-- <text class="iconfont icon-sousuo"></text> -->
			</view>
			<view class="title">
				钱包列表
			</view>
			<view class="close">
				<text class="iconfont icon-colse" @click="closePopup"></text>
			</view>
		</view>
		<view class="content">
			<view class="left">
				<scroll-view class="scrollL" scroll-y="true">
					<view class="list">
						<view class="item" :class="{'act':i.chainId==walletChain.chainId}"
							v-for="(i,index) in allchains" :key="i" @tap="tab(i)">
							<image :src="'/static/images/chain/'+i.chainName+'.png'" mode="" class="icon"
								:class="{'gray':i.chainId!=walletChain.chainId}">
							</image>
						</view>
					</view>
				</scroll-view>
				<!-- <view class="manage">
					管理
				</view> -->
			</view>
			<view class="right">
				<view class="title">
					<view class="chainName">
						{{chainNameTitle}}
					</view>
					<view class="add">
						<image src="/static/images/home/coinadd.png" mode="" class="icon" @tap="openPopup"></image>
					</view>
				</view>
				<scroll-view class="scrollR" scroll-y="true">
					<view class="cell_list">
						<view class="cell_item" v-for="(i,index) in addressList" :key="index" @tap="switchAddress(i)"
							:style="{'backgroundColor':walletChain.wallteColor,'color':walletChain.textColor}">
							<view class="name">
								{{i.name}}
								<view class="observe" :style="{'borderColor':walletChain.textColor}"
									v-if="i.importMethod==4">观察钱包</view>
							</view>
							<view class="addressBox">
								<view class="cell_left">
									<view class="address">
										{{$utils.formatAddress(i.address)}}
									</view>
									<view class="copy">
										<text class="iconfont icon-fuzhi" @tap.stop="copy(i.address)"></text>
										<!-- <image src="../../static/images/home/addcopy.png" mode="" class="icon"
										@tap.stop="copy(i.address)">
									</image> -->
									</view>
								</view>
								<view class="state" v-if="i.address==address&&i.chainId==chainId">
									<!-- <image src="../../static/images/home/active.png" mode="" class="icon"></image> -->
									<text class="iconfont icon-icon_duigou" @tap.stop="copy(i.address)"></text>
								</view>
							</view>
							<view class="balacne">
								{{ $utils.toTwoDecimalDown(balances[i.address]?balances[i.address]:0)}}
								{{walletChain.mainCoinName}}
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" class="popup" background-color="#F6F6F6" border-radius="10px 10px 0 0">
			<view class="btnBox">
				<view class="btn_ground">
					<view class="btn" @tap="importType">
						导入钱包
					</view>
					<view class="btn" @tap="createPass(2)">
						创建钱包
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: "switchWallet",
		data() {
			return {
				addressList: [],
				walletChain: null,
				balances: {}
			};
		},
		computed: {
			addressInfo() {
				return this.$store.getters.addressInfo;
			},
			allchains() {
				return this.$store.getters.getAllchains;
			},
			address() {
				return this.$store.getters.getAddress;
			},
			chainId() {
				return this.$store.getters.getChainId;
			},
			chainInfo() {
				return this.$store.getters.chainInfo
			},
			chainNameTitle() {
				return this.walletChain.chainName
			},
		},
		async mounted() {
			this.walletChain = this.chainInfo;
			this.getSelectChain()
		},
		methods: {
			async getBalance(address) {
				try {
					const res = await uni.$db.select('list', {
						from: 'choinList',
						where: [{
							address: `= "${address}"`,
							chainId: `= "${this.walletChain.chainId}"`,
							tokenaddress: `= "${this.$config.defaultAddress}"`
						}]
					});
					const balance = res[0]?.tokennum || 0; // 默认值为0
					this.$set(this.balances, address, balance); // 更新余额
				} catch (error) {
					this.$set(this.balances, address, 0); // 或者返回一个默认值
				}
			},
			closePopup() {
				this.$emit('closePopup');
			},
			getChainInfo(chainId) {
				return uni.getStorageSync('allchains').find(item => item.chainId == chainId);
			},
			switchAddress(wallet) {
				this.$store.commit('setChainId', wallet.chainId);
				this.$store.commit('setAddress', wallet.address);
				let rpclist = uni.getStorageSync('rpclist') || [];
				const foundChain = rpclist.find(chain => chain.chainId == wallet.chainId);
				this.$store.commit('setRpc', foundChain?.defultRPC);
				this.$updateWalletInfo()
				this.$emit('closePopup');
			},
			tab(i) {
				this.walletChain = i
				this.getSelectChain()
			},

			createPass(type) {
				this.$refs.popup.close()
				this.$emit('closePopup');
				const nameArray = this.addressList.map(item => item.name);
				const nextNumber = this.$utils.getNextChainNumber(nameArray, this.walletChain.chainName)
				let config = {
					address: "",
					privateKey: "",
					mnemonics: "",
					chainType: this.walletChain.chainType,
					chainName: this.walletChain.chainName,
					chainId: this.walletChain.chainId,
					name: `${this.walletChain.chainName}-${nextNumber}`,
					password: "",
					passwordTilp: "",
					importMethod: type
				}
				const configStr = encodeURIComponent(JSON.stringify(config));
				uni.navigateTo({
					url: `/pages/createPass/createPass?type=${type}&configStr=${configStr}`
				})
			},
			importType() {
				this.$refs.popup.close()
				this.$emit('closePopup');
				const nameArray = this.addressList.map(item => item.name);
				const nextNumber = this.$utils.getNextChainNumber(nameArray, this.walletChain.chainName)
				let config = {
					address: "",
					privateKey: "",
					mnemonics: "",
					chainType: this.walletChain.chainType,
					chainName: this.walletChain.chainName,
					chainId: this.walletChain.chainId,
					name: `${this.walletChain.chainName}-${nextNumber}`,
					password: "",
					passwordTilp: "",
					importMethod: ""
				}
				const configStr = encodeURIComponent(JSON.stringify(config));
				uni.navigateTo({
					url: `/pages/importType/importType?configStr=${configStr}&defultRPC=${this.walletChain.defultRPC}`
				})
			},
			openPopup() {
				this.$refs.popup.open('bottom')
			},
			getSelectChain() {
				uni.$db.select('list', { // 普通查询
					from: 'addressList',
					where: [{
						chainId: `= "${this.walletChain.chainId}"`
					}]
				}).then(res => {
					this.addressList = res
					this.addressList.forEach(addressItem => {
						this.getBalance(addressItem.address); // 异步调用
					});
				})
			},
			copy(address) {
				uni.setClipboardData({
					data: address,
					success: () => {
						uni.showToast({
							title: '复制成功',
							icon: 'none',
						});
					},
					fail: () => {
						uni.showToast({
							title: '复制失败',
							icon: 'none',
						});
					},
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "/static/iconfont/iconfont.css";

	.switchWallet {
		.btnBox {
			.btn_ground {
				padding: 30upx 0;

				.btn {
					margin: 40upx 60upx;
					background: #FFF;
					text-align: center;
					line-height: 90upx;
					font-size: 28upx;
				}
			}
		}

		.titleBox {
			width: 100%;
			display: flex;
			justify-content: space-between;
			padding: 30upx 40upx;
			box-sizing: border-box;
			color: #3D3D3D;
			font-size: 32upx;

			.title {}

		}

		.content {
			width: 100%;
			height: 60vh;
			display: flex;

			.left {
				width: 136upx;
				background: #F7F7F7;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.scrollL {
					height: 100%;
				}

				.list {
					flex-wrap: 1;

					.act {
						background: #FFF;
					}

					.item {
						display: flex;
						justify-content: center;
						align-items: center;
						height: 120upx;

						.icon {
							width: 68upx;
							height: 68upx;
						}

						.gray {
							filter: grayscale(100%);
						}
					}
				}

				.manage {
					height: 120upx;
					display: flex;
					justify-content: center;
					align-items: center;
					background: #fff;

				}
			}

			.right {
				flex: 1;
				background: #fff;
				padding: 0 20upx;
				.title {
					display: flex;
					justify-content: space-between;
					background: #FFF;
					padding: 20upx 0;

					.add {
						width: 46upx;
						height: 46upx;
						border-radius: 23upx;
						background-color: #F5F6F8;
						display: flex;
						justify-content: center;
						align-items: center;

						.icon {
							width: 32upx;
							height: 32upx;
						}
					}
				}

				.scrollR {
					height: calc(60vh - 86upx);
				}

				.cell_list {
					padding-bottom: 20upx;

					.cell_item {
						margin-top: 20upx;
						background-color: #000;
						color: #FFF;
						padding: 20upx 26upx;
						border-radius: 20upx;

						.name {
							font-size: 28upx;
							display: flex;
							align-items: center;
							margin-bottom: 10upx;

							.observe {
								margin-left: 20upx;
								padding: 0 10upx;
								border-radius: 5upx;
								border: 1px solid #FFF;
								font-size: 20upx;
							}
						}

						.balacne {
							text-align: right;
							font-size: 28upx;
							margin-top: 28upx;
						}

						.addressBox {
							display: flex;
							align-items: center;
							justify-content: space-between;

							.cell_left {
								display: flex;
								align-items: center;

								.address {
									font-size: 20upx;
								}

								.copy {
									display: flex;
									margin-left: 20upx;

									.iconfont {
										font-size: 20upx;
									}

									.icon {
										width: 24upx;
										height: 24upx;
									}
								}
							}

							.state {
								display: flex;

								.icon {
									width: 40upx;
									height: 40upx;
								}
							}
						}
					}
				}
			}
		}
	}
</style>